from django.db.models import Q

from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from unicodedata import category

from course.models import Course
from course.ser import CourseSer
from home.models import Category
from home.ser import CategorySerS, CategorySer


# Create your views here.
class CategoryView(APIView):
    def get(self, request):
        data = Category.objects.filter(is_del=False, parent=None).order_by('order')
        ser = CategorySerS(data, many=True)
        return Response(ser.data)


class CateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if id != '0':
            data = Category.objects.filter(is_del=False, parent=id).order_by('order')
        else:
            data = Category.objects.exclude(is_del=False, parent=None).order_by('order')
        ser = CategorySerS(data, many=True)
        return Response(ser.data)


class CoursePage(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'


class CourseView(ListAPIView):
    queryset = Course.objects.filter(is_del=False)
    serializer_class = CourseSer
    pagination_class = CoursePage

    def get_queryset(self):
        query = Q()
        cate = self.request.GET.get('cate')
        direction = self.request.GET.get('direction')
        ordering=self.request.GET.get('ordering','')
        level=self.request.GET.get('level','')
        if cate != '0':
            query &= Q(category=cate)
        if direction != '0':
            data = Category.objects.filter(is_del=False, parent=direction).values_list('id')
            # catelistID = []
            # for i in data:
            #     catelistID.append(i.id)
            query &= Q(category__in=data)
        if level:
            query &= Q(level=level)
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        else:
            return self.queryset.filter(query)

class DtailView(APIView):
    def get(self, request):
        data=Course.objects.filter(id=request.GET.get('id')).first()
        ser=CourseSer(data)
        return Response(ser.data)